#include "StdAfx.h"
#include "Polynome.h"


Polynome::Polynome(){

}

Polynome::Polynome(Monome & m){
	_monomes.push_back(m);
}

Polynome::Polynome(Polynome & p){
	_monomes = p._monomes;
}

Polynome::~Polynome(void){
}

Polynome & Polynome::operator= (const Polynome & p){
	_monomes = p._monomes;
	return *this;
}

Polynome Polynome::operator+ (const Polynome & p) const{
	Polynome poly;
	poly._monomes = _monomes;

	for (list<Monome>::const_iterator i = p._monomes.begin(); i != p._monomes.end(); ++i){
		poly.Ajouter(*i);
	}
	return poly;
}

Polynome Polynome::operator+ (const Monome & m) const{
	Polynome poly;
	poly._monomes = _monomes;

	poly.Ajouter(m);

	return poly;
}

void Polynome::Ajouter(const Monome & m){
	for (list<Monome>::iterator i = _monomes.begin(); i != _monomes.end(); ++i){
		if (i->GetExp() == m.GetExp()){
			*i = *i + m;
			return;
		}else if (i->GetExp() < m.GetExp())
		{
			_monomes.insert(i,m);
			return;
		}
	}
	_monomes.push_back(m);
}

Polynome Polynome::operator* (const Polynome & p) const{
	Polynome resultats;

	for (list<Monome>::const_iterator i2 = p._monomes.begin(); i2 != p._monomes.end(); ++i2){
		for (list<Monome>::const_iterator i1 = _monomes.begin(); i1 != _monomes.end(); ++i1){
			resultats.Ajouter(*i2 * *i1);
		}
	}
	return resultats;
}

string Polynome::ToString () const{
	stringstream s;
	for (list<Monome>::const_iterator i = _monomes.begin(); i != _monomes.end(); ++i){
		if ( i != _monomes.begin()){
			s << " + ";
		}
		s << ((Monome)*i) ;
	}
	return s.str();
}

unsigned Polynome::GetTaille() const{
	return _monomes.size();
}

Monome & Polynome::GetMonome(const unsigned pos ) const{
	if ( _monomes.size() > pos){
		list<Monome>::const_iterator it = _monomes.begin();
		advance(it, pos);
		return ((Monome)*it);
	}
	else
		throw exception("En dehors de la liste");	
}

double Polynome::eval(const double x) const{
	double tmp = 0.0;
	for (list<Monome>::const_iterator i = _monomes.begin(); i != _monomes.end(); ++i){
		tmp += pow(x * i->GetCoef().GetNumerateur() / i->GetCoef().GetDenominateur(),i->GetExp());
	}
	return tmp;
}

std::ostream & operator<<(std::ostream & flot,const Polynome & p){
	flot << p.ToString();
	return flot;
}
